﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IdentityModel.Selectors;
using System.Security.Cryptography.X509Certificates;
using System.IdentityModel.Tokens;

namespace Veracruz.IdentityModel
{
    // HACK : Copy from Microsoft Code Name Zermatt Samples (CustomX509CertificateValidator).
    public class ActAsSigningCertificateValidator : X509CertificateValidator
    {
        X509Certificate2 _issuerCert;

        public ActAsSigningCertificateValidator(string subjectName)
        {
            _issuerCert = CertificateHelper.GetCertificate(StoreName.My, StoreLocation.LocalMachine, subjectName);
            if (_issuerCert == null)
            {
                throw new ArgumentException(String.Format("Cannot find certificate with subject name {0}", subjectName));
            }
        }

        /// <summary>
        /// Only allow the STS signing certificate to be used for incoming ActAs tokens
        /// </summary>
        /// <param name="certificate"></param>
        public override void Validate(X509Certificate2 certificate)
        {
            if (certificate.Thumbprint != _issuerCert.Thumbprint)
            {
                throw new SecurityTokenException("Issuer certificate validation failed");
            }
        }
    }
}
